package com.itheima.web.filter;

import com.itheima.domain.User;
import com.itheima.service.ServiceIml;
import com.itheima.service.UserService;
import com.itheima.utils.CookUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter( "/*")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;

        //0. 判断用户是否已经登录了
        Object u = request.getSession().getAttribute("user");
        if (u != null) {
            // 用户已经登录了
            chain.doFilter(req, resp);
            return;
        }

        // 用没有登录
        // 读取Cookie
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookUtils.getCookieByName("autoLoginCookie", cookies);

        if (cookie == null) {
            chain.doFilter(req, resp);
            return;
        }

        // 有用户信息,调用service
        String value = cookie.getValue();
        User user = new User();
        user.setUsername(value.split("&")[0]);
        user.setPassword(value.split("&")[1]);

        UserService service=new ServiceIml();
        User existUser = service.login(user);

        // cookie的用户信息和数据库不一致 (可能用户修改了密码)
        if (existUser == null) {
            chain.doFilter(req, resp);
            return;
        }

        // 用户存在, 将用户存入到session域中
        request.getSession().setAttribute("user", existUser);
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}


